package utils

import (
	"fmt"
	"reflect"
	"strconv"
)

type TypeConv struct {
	Data string
}

func (tc *TypeConv) ToString() string {
	return tc.Data
}

func (tc *TypeConv) ToInt() int {
	var data, _ = strconv.Atoi(tc.Data)
	return data
}

func (tc *TypeConv) ToFloat64() float64 {
	var data, _ = strconv.ParseFloat(tc.Data, 64)
	return data
}

func (tc *TypeConv) ToInt64() int64 {
	var data, _ = strconv.Atoi(tc.Data)
	return int64(data)
}

//判断元素是否在数组中存在
func InArray(one interface{}, arr interface{}) bool {
	switch arr.(type) {
	case []string:
		tmp := map[string]string{}
		a := one.(string)
		b := arr.([]string)
		Blen := len(b)
		for i := 0; i < Blen; i++ {
			tmp[b[i]] = "ok"
		}
		if tmp[a] == "ok" {
			return true
		}
		break
	case []int:
		tmp := map[int]string{}
		a := one.(int)
		b := arr.([]int)
		Blen := len(b)
		for i := 0; i < Blen; i++ {
			tmp[b[i]] = "ok"
		}
		if tmp[a] == "ok" {
			return true
		}
		break
	case []int64:
		tmp := map[int64]string{}
		a := one.(int64)
		b := arr.([]int64)
		Blen := len(b)
		for i := 0; i < Blen; i++ {
			tmp[b[i]] = "ok"
		}
		if tmp[a] == "ok" {
			return true
		}
		break
	case []float32:
		tmp := map[float32]string{}
		a := one.(float32)
		b := arr.([]float32)
		Blen := len(b)
		for i := 0; i < Blen; i++ {
			tmp[b[i]] = "ok"
		}
		if tmp[a] == "ok" {
			return true
		}
		break
	case []float64:
		tmp := map[float64]string{}
		a := one.(float64)
		b := arr.([]float64)
		Blen := len(b)
		for i := 0; i < Blen; i++ {
			tmp[b[i]] = "ok"
		}
		if tmp[a] == "ok" {
			return true
		}
		break
	default:

	}

	return false
}
func StructToMapReflect(in interface{}, tagName string) (map[string]interface{}, error) {
	out := make(map[string]interface{})

	v := reflect.ValueOf(in)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	if v.Kind() != reflect.Struct { // 非结构体返回错误提示
		return nil, fmt.Errorf("ToMap only accepts struct or struct pointer; got %T", v)
	}

	t := v.Type()
	// 遍历结构体字段
	// 指定tagName值为map中key;字段值为map中value
	for i := 0; i < v.NumField(); i++ {
		fi := t.Field(i)
		if tagValue := fi.Tag.Get(tagName); tagValue != "" {
			out[tagValue] = v.Field(i).Interface()
		}
	}
	return out, nil
}
